// pages/history/history.js
import {GetFatDetailList,GetDistinctFatDetailDate} from "../../api/api";
import {getCurrentDate,mGetDate} from "../../utils/timeTool";
import getNextDate from "../../utils/getNextDate";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 有历史记录的日期
    selected: [],
    date:new Date(),
    isOpen:false,
    isContrast:false,
    calShow: true, // 日历组件是否打开
    dateShow: false, // 日期是否选择
    selectDay: '', // 当前选择日期
    canlender: {
      "weeks": []
    },
    myDate:[],
    historyData:[],
    historyDatas:[],
    showData:{},
    contrastData:[],
    currentDateTitle:"",
    currentDateContent:[]
  },

  //开始对比
  startContrast(){
    let {contrastData}=this.data; 
    if (contrastData.length==2) {
      wx.setStorageSync("contrastData", contrastData);
      wx.navigateTo({
        url: '../../pages/datacontrast/datacontrast'
      });
    }else{
    }
  },
  //删除对比值
  delContrastData(e){
    let {contrastData,showData,historyDatas}=this.data;
    let id=e.target.dataset.id;
    let index= contrastData.findIndex(item=>item.id==id);
    contrastData.splice(index,1);
    //要清楚选中状态必须把historyDatas里面的也清了
    historyDatas.forEach((val)=>{
      val.content.forEach((item)=>{
          if (item.id==id) {
            item.checked=false;
          }
      })  
    })
    if(showData.content){
      showData.content.forEach((item)=>{
        if (item.id==id) {
          item.checked=false;
        }
      })
    }
    this.setData({
      showData,
      historyDatas,
      contrastData
    })
  },
  //切换数据的选中状态
  checkedRadio(e){
    let {showData,contrastData}=this.data;
    let id=e.target.dataset.id;
      showData.content.forEach((item)=>{
        if (item.id==id) {
            if(!item.checked&&contrastData.length==2){  //判断是否对比的值是否有两个了并且checked为false(就是两个的时候不能添加对比)
              return;
            }
              item.checked=!item.checked;
            if (item.checked) {//如果为true的话就添加数据
              contrastData.push(item);
            }else{
              let index=contrastData.findIndex(item=>item.id==id);
              contrastData.splice(index,1);
            }
          }
      })
    this.setData({
      contrastData,
      showData
    })
  },
  // 点击对比按钮
  clickContrast(){
    this.setData({
      isContrast:true
    })
  },
  cancelContrast(){
    this.setData({
      isContrast:false
    })
  },
  dateSelection() {
    if (this.data.isOpen) {
      return
    }
    let self = this;
    if (self.data.calShow) {
      self.setData({
        calShow: false
      }, () => {
        setTimeout(() => {
          self.setData({
            dateShow: true
          }, () => {
            self.triggerEvent('select', { ischeck: !self.data.calShow })
          })
        }, 100)
      })
    } else {
      self.setData({
        dateShow: false
      }, () => {
        setTimeout(() => {
          self.setData({
            calShow: true
          }, () => {
            self.triggerEvent('select', { ischeck: !self.data.calShow })
          })
        }, 300)
      })
    }

  },
  selectDay(e) {

    let index = e.currentTarget.dataset.index;
    let week = e.currentTarget.dataset.week;
    let ischeck = e.currentTarget.dataset.ischeck;
    let canlender = this.data.canlender;
    if (!ischeck) return false;
    let month = canlender.weeks[week][index].month < 10 ? "0" + canlender.weeks[week][index].month : canlender.weeks[week][index].month
    let date = canlender.weeks[week][index].date < 10 ? "0" + canlender.weeks[week][index].date : canlender.weeks[week][index].date
    this.getWeek(canlender.year + "-" + month + "-" + date);
  },
  packup() {
       this.setData({
          dateShow: false
       })
    let self = this;
    if (this.data.isOpen) {
      let year = self.data.canlender.year + "-" + self.data.canlender.month + "-" + self.data.canlender.date
      let _date = self.getDate(year, 0);
      // self.getWeek(_date);
      return
    }
    self.setData({
      dateShow: false
    }, () => {
      setTimeout(() => {
        self.setData({
          calShow: true
        }, () => {
          let year = self.data.canlender.year + "-" + self.data.canlender.month + "-" + self.data.canlender.date
          let _date = self.getDate(year, 0);
          // self.getWeek(_date);
          self.triggerEvent('select', { ischeck: !self.data.calShow })
        })
      }, 300)
    })
  },
  // 返回今天
  backtoday() { this.getWeek(new Date()); },
  // 前一天||后一天
  dataBefor(e) {
    let num = 0;
    let types = e.currentTarget.dataset.type;

    if (e.currentTarget.dataset.id === "0") {
      num = -1;
    } else {
      num = 1
    }
    let year = this.data.canlender.year + "-" + this.data.canlender.month + "-" + this.data.canlender.date
    let _date = this.getDate(year, num, types === 'month' ? "month" : "day");
    this.getWeek(_date);
  },
  // 获取日历内容
  getWeek(dateData) {
    this.getShowData(dateData);
    let selected = this.data.selected
    let a = new Date()
    // 判断当前是 安卓还是ios ，传入不容的日期格式
    if (typeof dateData !== 'object') {
      dateData = dateData.replace(/-/g, "/")
    }
    let _date = new Date(dateData);
    let year = _date.getFullYear(); //年
    let month = _date.getMonth() + 1;  //月
    let date = _date.getDate();//日
    let day = _date.getDay();// 天
    let canlender = [];
    let dates = {
      firstDay: new Date(year, month - 1, 1).getDay(),
      lastMonthDays: [],// 上个月末尾几天
      currentMonthDys: [], // 本月天数
      nextMonthDays: [], // 下个月开始几天
      endDay: new Date(year, month, 0).getDay(),
      weeks: []
    }

    // 循环上个月末尾几天添加到数组
    for (let i = dates.firstDay; i > 0; i--) {
      dates.lastMonthDays.push({
        'date': new Date(year, month, -i).getDate() + '',
        'month': month - 1
      })
    }
    // 循环本月天数添加到数组
    for (let i = 1; i <= new Date(year, month, 0).getDate(); i++) {
      let have = false;
      for (let j = 0; j < selected.length; j++) {
        let selDate = selected[j].split('-');

        if (Number(year) === Number(selDate[0]) && Number(month) === Number(selDate[1]) && Number(i) === Number(selDate[2])) {
          have = true;
        }
      }
      dates.currentMonthDys.push({
        'date': i + "",
        'month': month,
        have
      })
    }
    // 循环下个月开始几天 添加到数组
    for (let i = 1; i < 7 - dates.endDay; i++) {
      dates.nextMonthDays.push({
        'date': i + '',
        'month': month + 1
      })
    }

    canlender = canlender.concat(dates.lastMonthDays, dates.currentMonthDys, dates.nextMonthDays)
    // 拼接数组  上个月开始几天 + 本月天数+ 下个月开始几天
    for (let i = 0; i < canlender.length; i++) {
      if (i % 7 == 0) {
        dates.weeks[parseInt(i / 7)] = new Array(7);
      }
      dates.weeks[parseInt(i / 7)][i % 7] = canlender[i]
    }


    // 渲染数据
    this.setData({
      selectDay: month + "月" + date + "日",
      "canlender.weeks": dates.weeks,
      'canlender.month': month,
      'canlender.date': date,
      "canlender.day": day,
      'canlender.year': year,
    })
    // console.log(this.data.selectDay);
    // let {year,month,day}=this.data;
    let mymonth=this.data.canlender.month<10?"0"+this.data.canlender.month:this.data.canlender.month;
    let mydate=this.data.canlender.date<10?"0"+this.data.canlender.date:this.data.canlender.date;
    let currentDate=this.data.canlender.year+'-'+mymonth+'-'+mydate;
    // console.log(currentDate);
    this.getCurrentData(currentDate);
    month = month < 10 ? "0" + month : month
    date = date < 10 ? "0" + date : date
    this.triggerEvent('getdate', { year, month, date })
    // this.getCurrentData();
  },
  /**
   * 时间计算
   */
  getDate(date, AddDayCount, str = 'day') {
    if (typeof date !== 'object') {
      date = date.replace(/-/g, "/")
    }
    let dd = new Date(date)
    switch (str) {
      case 'day':
        dd.setDate(dd.getDate() + AddDayCount)// 获取AddDayCount天后的日期
        break;
      case 'month':
        dd.setMonth(dd.getMonth() + AddDayCount)// 获取AddDayCount天后的日期
        break;
      case 'year':
        dd.setFullYear(dd.getFullYear() + AddDayCount)// 获取AddDayCount天后的日期
        break;
    }
    let y = dd.getFullYear()
    let m = (dd.getMonth() + 1) < 10 ? '0' + (dd.getMonth() + 1) : (dd.getMonth() + 1)// 获取当前月份的日期，不足10补0
    let d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate()// 获取当前几号，不足10补0
    return y + '-' + m + '-' + d
  },

  // 获取展示的数据
  getShowData(date){
    let {historyDatas}=this.data; 
    this.setData({
      showData:{}
    })
    historyDatas.forEach((val)=>{
      if (val.date==date) {
          this.setData({
            showData:val
          })
          return;
      }
    })
  },
  //获取当前数据
  getCurrentData(currentDate){
    let TZCuserInfo= wx.getStorageSync('TZCuserInfo');
    if (TZCuserInfo) {
      wx.showLoading({
        title: '加载中',
        mask:true
      })
      this.setData({
        currentDateTitle:currentDate
      })
      
      let data={
        fatid: TZCuserInfo.id,
        startdate: currentDate,
        enddate:getNextDate(currentDate,1),
      }
      
      // console.log(data);
      // let selected=[]; 
      GetFatDetailList(data,(e)=>{
        // console.log(e)
          if(e.data){
            e.data.reverse().forEach((val,index)=>{
              e.data[index].time=val.createdate.substring(11,16);
              e.data[index].exactTime=val.createdate.substring(11,19);
              e.data[index].date=val.createdate.substring(0,10);
            })
            this.setData({
              currentDateContent:e.data
            })
            wx.hideLoading();
          }else{
            this.setData({
              currentDateContent:[]
            })
            wx.hideLoading();
          }

      });
    }
  },
  addCompare(e){
    let {contrastData}=this.data;
    let val=e.currentTarget.dataset.val;
    let flag=true;
    if (contrastData) {
      contrastData.forEach((item)=>{
        if (val.id==item.id) {
            flag=false;
            return;
        }
      })

    }
    if (contrastData.length==2||!flag) {
      return;
    }
    contrastData.push(val);
    this.setData({
      contrastData
    })
  },
  jumpAnalyse(e){
    let val=JSON.stringify(e.currentTarget.dataset.val);
    wx.navigateTo({
      url: `../analyse/analyse?val=${val}`,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (this.data.isOpen) {
      this.setData({
        calShow: false,
        dateShow: true
      })
    }
    let TZCuserInfo= wx.getStorageSync('TZCuserInfo');
    if(TZCuserInfo){
      GetDistinctFatDetailDate(TZCuserInfo.id,(e)=>{
      let selected=[];
        e.data.forEach((val)=>{
          selected.push(val.createdate);
        })
        this.setData({
          selected
        })
      this.getWeek(new Date())  //获取当前
      })
   
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})